<template>
  <div class="category-container">
    <!-- 顶部标题和搜索 -->
    <div class="header">
      <div class="title">分类</div>
      <van-icon name="search" size="24" />
    </div>

    <div class="content">
      <!-- 左侧分类导航 -->
      <div class="sidebar">
        <div
          v-for="(item, index) in parentCategories"
          :key="item.id"
          :class="['sidebar-item', activeCategory === index ? 'active' : '']"
          @click="switchCategory(index)"
        >
          <div class="sidebar-item-text">{{ item.categoryName }}</div>
          <div v-if="activeCategory === index" class="active-indicator"></div>
        </div>
      </div>

      <!-- 右侧内容区域 -->
      <div class="main-content">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-empty v-if="loading" description="加载中..." />
          <van-empty v-else-if="!currentChildren.length" description="暂无分类数据" />
          <template v-else>
            <!-- 新品标签 -->
            <div v-if="activeParent" class="new-products-label">
              <div class="red-line"></div>
              <span>{{ activeParent.categoryName }}新品</span>
            </div>

            <!-- 子分类列表 -->
            <div class="subcategory-grid">
              <div
                v-for="item in currentChildren"
                :key="item.id"
                class="subcategory-item"
                @click="onSubCategoryClick(item)"
              >
                <van-image
                  :src="item.categoryImage"
                  width="70"
                  height="70"
                  fit="cover"
                />
                <p class="subcategory-name">{{ item.categoryName }}</p>
              </div>
            </div>
          </template>
        </van-pull-refresh>
      </div>
    </div>

    <!-- 底部导航栏 -->
    <van-tabbar v-model="activeTabbar" route>
      <van-tabbar-item icon="home-o" to="/ncwuShop/home">首页</van-tabbar-item>
      <van-tabbar-item icon="apps-o" to="/ncwuShop/category">分类</van-tabbar-item>
      <van-tabbar-item icon="cart-o" to="/ncwuShop/cart">购物车</van-tabbar-item>
      <van-tabbar-item icon="user-o" to="/ncwuShop/mine">我的</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { listCategory } from '@/api/categoryManage/category';

const router = useRouter();
const { proxy } = getCurrentInstance();
const activeTabbar = ref(1); // 设置当前激活的标签为分类
const activeCategory = ref(0); // 当前选中的分类索引
const refreshing = ref(false);
const loading = ref(false);
const allCategories = ref([]); // 所有分类数据

// 获取父级分类（parentId=0）
const parentCategories = computed(() => {
  return allCategories.value.filter(item => item.parentId === 0 || item.parentId === null);
});

// 获取当前选中的父级分类
const activeParent = computed(() => {
  if (parentCategories.value.length > 0 && activeCategory.value < parentCategories.value.length) {
    return parentCategories.value[activeCategory.value];
  }
  return null;
});

// 获取当前父级分类的子分类
const currentChildren = computed(() => {
  if (!activeParent.value) return [];
  return allCategories.value.filter(item => item.parentId === activeParent.value.id);
});

// 切换分类
const switchCategory = (index) => {
  activeCategory.value = index;
};

// 下拉刷新
const onRefresh = () => {
  getCategories();
};

// 点击子分类
const onSubCategoryClick = (category) => {
  console.log('选择子分类:', category);
  // 跳转到对应分类的商品列表页
  router.push({
    path: '/ncwuShop/product/list',
    query: { categoryId: category.id }
  });
};

// 获取所有分类数据
const getCategories = () => {
  loading.value = true;
  listCategory().then(response => {
    if (response.code === 200) {
      const categoriesData = response.data || [];
      
      // 处理图片路径
      allCategories.value = categoriesData.map(item => {
        if (item.categoryImage && item.categoryImage.startsWith('/profile/upload')) {
          // 转换图片路径格式
          item.categoryImage = "http://www.zyf.com" + item.categoryImage.replace("/profile", "");
        }
        return item;
      });
      
      // 默认选择第一个父级分类
      if (parentCategories.value.length > 0) {
        activeCategory.value = 0;
      }
    } else {
      console.error('获取商品类目列表失败:', response.msg);
    }
    loading.value = false;
    refreshing.value = false;
  }).catch(error => {
    console.error('获取商品类目列表失败', error);
    loading.value = false;
    refreshing.value = false;
  });
};

onMounted(() => {
  getCategories();
  console.log(allCategories)
  console.log(parentCategories)
});
</script>

<style scoped>
.category-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: rgb(245, 245, 245);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 16px;
  background-color: #fff;
  height: 44px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.title {
  font-size: 20px;
  font-weight: bold;
}

.content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 左侧导航栏样式 */
.sidebar {
  width: 85px;
  height: 100%;
  background-color: #f5f5f5;
  overflow-y: auto;
}

.sidebar-item {
  display: flex;
  align-items: center;
  height: 50px;
  text-align: center;
  font-size: 16px;
  cursor: pointer;
  position: relative;
}

.sidebar-item-text {
  width: 100%;
  padding: 0 5px;
}

.sidebar-item.active {
  background-color: #fff;
  color: #ff2c2c;
  font-weight: bold;
}

.active-indicator {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 16px;
  background-color: #ff2c2c;
  border-radius: 0 4px 4px 0;
}

/* 右侧内容区域样式 */
.main-content {
  flex: 1;
  padding: 15px 10px;
  overflow-y: auto;
  background-color: #fff;
}

.new-products-label {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
}

.red-line {
  width: 4px;
  height: 16px;
  background-color: #ff2c2c;
  margin-right: 6px;
  border-radius: 2px;
}

.subcategory-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
}

.subcategory-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}

.subcategory-name {
  margin-top: 8px;
  font-size: 14px;
  text-align: center;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>